﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Mail;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Forms;
using CheckBox=System.Windows.Controls.CheckBox;
using ContextMenu=System.Windows.Forms.ContextMenu;
using TextBox=System.Windows.Controls.TextBox;

namespace ITProf.QuickMailer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private static readonly DependencyProperty CanSendProperty = DependencyProperty.Register("CanSend",
                                                                                                 typeof (bool),
                                                                                                 typeof (MainWindow));

        private Mailer googleMailer;

        private WindowState storedWindowState = WindowState.Normal;
        private NotifyIcon trayIcon;
        private ContextMenu trayMenu;

        public MainWindow()
        {
            InitializeMailer();
            Title = Strings.ApplicationTitle;
            InitializeTrayIcon();
        }

        internal bool CanSend
        {
            get { return (bool) GetValue(CanSendProperty); }
            set { SetValue(CanSendProperty, value); }
        }

        private string MailSubject
        {
            get { return tbSubject.Text.Trim(); }
            set { tbSubject.Text = value; }
        }

        private string MailMessage
        {
            get
            {
                var range = new TextRange(tbText.Document.ContentStart, tbText.Document.ContentEnd);
                return range.Text.Trim();
            }
            set
            {
                var range = new TextRange(tbText.Document.ContentStart, tbText.Document.ContentEnd);
                range.Text = value;
            }
        }

        private void InitializeSettings()
        {
            chkMail0.IsChecked = SettingsManager.Instance.SendToMail0;
            chkMail1.IsChecked = SettingsManager.Instance.SendToMail1;
            chkMail2.IsChecked = SettingsManager.Instance.SendToMail2;
            chkMail3.IsChecked = SettingsManager.Instance.SendToMail3;
            chkMail4.IsChecked = SettingsManager.Instance.SendToMail4;
            chkAutoClear.IsChecked = SettingsManager.Instance.AutoClear;
            tbMail0.Text = SettingsManager.Instance.Mail0;
            tbMail1.Text = SettingsManager.Instance.Mail1;
            tbMail2.Text = SettingsManager.Instance.Mail2;
            tbMail3.Text = SettingsManager.Instance.Mail3;
            tbMail4.Text = SettingsManager.Instance.Mail4;
            Height = SettingsManager.Instance.MainWindowHeight;
            Width = SettingsManager.Instance.MainWindowWidth;
        }

        private void InitializeMailer()
        {
            googleMailer = new Mailer
                               {
                                   SmtpServerPort = Settings.Default.SmtpServerPort,
                                   SmtpServerHost = Settings.Default.SmtpServerHost,
                                   UserName = SecureHelper.ConvertToSecureString(Settings.Default.SmtpServerUserName),
                                   UserPassword =
                                       SecureHelper.ConvertToSecureString(Settings.Default.SmtpServerPassword),
                                   UseSSL = Settings.Default.SmtpServerUserSSL
                               };
        }

        private void OnClose(object sender, CancelEventArgs args)
        {
            trayIcon.Dispose();
            trayIcon = null;
        }

        private void OnStateChanged(object sender, EventArgs args)
        {
            if (WindowState == WindowState.Minimized)
            {
                Hide();
            }
            else
            {
                storedWindowState = WindowState;
            }
        }

        private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            //CheckTrayIcon();
        }

        private void OnTrayIconClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Restore();
            }
            else if (e.Button == MouseButtons.Right)
            {
            }
        }

        private void Restore()
        {
            Show();
            WindowState = storedWindowState;
        }

        private void CheckTrayIcon()
        {
            ShowTrayIcon(!IsVisible);
        }

        private void ShowTrayIcon(bool show)
        {
            if (trayIcon != null)
            {
                trayIcon.Visible = show;
            }
        }

        private void InitializeTrayIcon()
        {
            trayMenu = new ContextMenu();
            trayMenu.MenuItems.Add("Restore", (o, args) => Restore());
            trayMenu.MenuItems.Add("-");
            trayMenu.MenuItems.Add("Exit", (o, args) => Close());
            trayIcon = new NotifyIcon
                           {
                               BalloonTipText = Strings.ApplicationDescription,
                               BalloonTipTitle = Strings.ApplicationTitle,
                               Text = Strings.ApplicationTitle,
                               Icon = Images.App,
                               ContextMenu = trayMenu
                           };
            trayIcon.MouseClick += OnTrayIconClick;
            CheckTrayIcon();
        }

        private void OnSendClick(object sender, RoutedEventArgs e)
        {
            if (MailSubject.Length == 0)
            {
                ShowHint("Enter message subject.", ToolTipIcon.Warning, 1500);
                tbSubject.Focus();
                return;
            }
            if (MailMessage.Length == 0)
            {
                ShowHint("Enter message body.", ToolTipIcon.Warning, 1500);
                tbText.Focus();
                return;
            }
            WindowState = WindowState.Minimized;
            try
            {
                var recipients = new List<string>();
                if (chkMail0.IsChecked.HasValue && chkMail0.IsChecked.Value)
                {
                    recipients.Add(tbMail0.Text);
                }
                if (chkMail1.IsChecked.HasValue && chkMail1.IsChecked.Value)
                {
                    recipients.Add(tbMail1.Text);
                }
                if (chkMail2.IsChecked.HasValue && chkMail2.IsChecked.Value)
                {
                    recipients.Add(tbMail2.Text);
                }
                if (chkMail3.IsChecked.HasValue && chkMail3.IsChecked.Value)
                {
                    recipients.Add(tbMail3.Text);
                }
                if (chkMail4.IsChecked.HasValue && chkMail4.IsChecked.Value)
                {
                    recipients.Add(tbMail4.Text);
                }
                ShowHint("Sending to " + recipients.AsString() + "...", ToolTipIcon.Info, 0);
                googleMailer.Send(MailSubject,
                    MailMessage, 
                    Settings.Default.FromEmail, 
                    Settings.Default.FromName,
                                  recipients,
                                  Settings.Default.ReplyTo,
                                  MailPriority.Normal);
            }
            catch (Exception ex)
            {
                ShowHint(ex.Message, ToolTipIcon.Error, 3000);
                Restore();
                return;
            }
            if (chkAutoClear.IsChecked.HasValue && chkAutoClear.IsChecked.Value)
            {
                MailSubject = "";
                MailMessage = "";
            }
            ShowHint("Message has been sent.", ToolTipIcon.Info, 1500);
        }

        private void ShowHint(string hint, ToolTipIcon icon, int timeout)
        {
            if (trayIcon != null)
            {
                trayIcon.ShowBalloonTip(timeout, Strings.ApplicationTitle, hint, icon);
            }
            lblStatus.Content = hint;
            lblStatus.ToolTip = hint;
        }

        private void chkMail0_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.SendToMail0 = chkMail0.IsChecked.HasValue && chkMail0.IsChecked.Value;
        }

        private void chkMail1_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.SendToMail1 = chkMail1.IsChecked.HasValue && chkMail1.IsChecked.Value;
        }

        private void chkMail2_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.SendToMail2 = chkMail2.IsChecked.HasValue && chkMail2.IsChecked.Value;
        }

        private void chkMail3_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.SendToMail3 = chkMail3.IsChecked.HasValue && chkMail3.IsChecked.Value;
        }

        private void chkMail4_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.SendToMail4 = chkMail4.IsChecked.HasValue && chkMail4.IsChecked.Value;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
        }

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            SettingsManager.Instance.MainWindowHeight = e.NewSize.Height;
            SettingsManager.Instance.MainWindowWidth = e.NewSize.Width;
        }

        private void tbMail0_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.Mail0 = ((TextBox) sender).Text;
        }

        private void tbMail1_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.Mail1 = ((TextBox) sender).Text;
        }

        private void tbMail2_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.Mail2 = ((TextBox) sender).Text;
        }

        private void tbMail3_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.Mail3 = ((TextBox) sender).Text;
        }

        private void tbMail4_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsManager.Instance.Mail4 = ((TextBox) sender).Text;
        }

        private void OnAutoClearChecked(object sender, RoutedEventArgs e)
        {
            var checkbox = (CheckBox) sender;
            SettingsManager.Instance.AutoClear = checkbox.IsChecked.HasValue && checkbox.IsChecked.Value;
        }

        private void UpdateDependencyProperties()
        {
            CanSend = MailSubject.Length > 0 &&
                      MailMessage.Length > 0 &&
                      ((chkMail0.IsChecked.IsTrue() && tbMail0.Text.Length > 0) ||
                       (chkMail1.IsChecked.IsTrue() && tbMail1.Text.Length > 0) ||
                       (chkMail2.IsChecked.IsTrue() && tbMail2.Text.Length > 0) ||
                       (chkMail3.IsChecked.IsTrue() && tbMail3.Text.Length > 0) ||
                       (chkMail4.IsChecked.IsTrue() && tbMail4.Text.Length > 0));
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateDependencyProperties();
        }

        private void UpdateDependencyPropertiesRequest(object sender, RoutedEventArgs e)
        {
            UpdateDependencyProperties();
        }

        private void wndMain_Initialized(object sender, EventArgs e)
        {
            InitializeSettings();
        }
    }
}